package cn.mysite.mycompany.controller;


import cn.mysite.mycompany.entity.User;
import cn.mysite.mycompany.mapper.FUserMapper;
import cn.mysite.mycompany.service.CartService;
import cn.mysite.mycompany.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.hyperledger.fabric.sdk.exception.InvalidArgumentException;
import org.hyperledger.fabric.sdk.exception.ProposalException;
import org.hyperledger.fabric.sdk.exception.TransactionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author  ChenChongFei
 * @since 2021-03-13
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private FUserMapper fUserMapper;

    @Autowired
    private CartService cartService;

    @PostMapping("/login")
    public String login(String loginName, String password, HttpSession session) throws TransactionException, ProposalException, InvalidArgumentException {
        QueryWrapper wrapper=new QueryWrapper();
        wrapper.eq("login_name",loginName);
        wrapper.eq("password",password);
        User user=userService.getOne(wrapper);
//        User user=null;
//        try {
//            user = fUserMapper.getOne(loginName, password);//
//        }
//        catch (Exception e)
//        {
//            return "login";
//        }
        if(user==null)
            return "login";
        else {
            session.setAttribute("user",user);
            return "redirect:/productCategory/list";
        }
    }

    @GetMapping("/logout")
    public String logout(HttpSession session){
        session.invalidate();
        return "login";

    }

    @PostMapping("/register")
    public String register(User user, Model model){
        boolean result=false;
        try{
            result=userService.save(user);
        }catch (Exception e){
            model.addAttribute("error",user.getLoginName()+"已存在，请重新输入");
        }
        if(result)
            return "login";
        else
            return "register";

    }

    @GetMapping("/userInfo")
    public ModelAndView userInfo(HttpSession session){
        User user = (User) session.getAttribute("user");
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("cartList",cartService.findAllCartVOByUserId(user.getId()));
        modelAndView.setViewName("userInfo");
        return modelAndView;
    }

}

